'''
    Goblinoid: Experience all of MediaGoblin on an Android Device
    Copyright (C) 2015 Dylan Jeffers

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

# handles new user's login information
from __future__ import print_function
from requests.exceptions import ConnectionError

from kivy.app import App
from kivy.lang import Builder
from kivy.properties import StringProperty, ObjectProperty, BooleanProperty
from kivy.uix.screenmanager import SlideTransition

from goblinoid.services.login_service import create_pump_profile, \
    add_credential, verify_new_user, has_credential, remove_credential
from goblinoid.root.goblinscreen import GoblinScreen, GoblinScreenWithManager
from goblinoid.root.goblinscreenmanager import GoblinScreenManager

from pypump.exception import PyPumpException
from pypump.client import ClientException
from requests.exceptions import ReadTimeout

Builder.load_file('goblinoid/login/loginview.kv')

USER_DIR = App.get_running_app().user_dir


class LoginManager(GoblinScreenManager):
    webfinger = StringProperty()
    verifier_token = StringProperty()
    error_message = StringProperty()

    def check_webfinger(self, webfinger):
        self.webfinger = webfinger
        try:
            if has_credential(USER_DIR, self.webfinger):
                self.pump = create_pump_profile(self.webfinger)
                App.get_running_app().pump_service.pump = self.pump
                add_credential(USER_DIR, self.webfinger)
                App.get_running_app().open_view('action', False)
            else:
                remove_credential(USER_DIR, self.webfinger)
                self.pump = create_pump_profile(self.webfinger)
                self.open_screen(name='verify', class_name='verify')
        except (ConnectionError, ReadTimeout), e:
            print(e)
            error_message = 'data connection error, please try again later'
            self.set_error_message(error_message)
        except PyPumpException, e1:
            print(e1)
            error_message = 'Invalid webfinger, please try again'
            self.set_error_message(error_message)
        except IndexError, e2:
            print(e2)
            error_message = 'Webfinger missing @'
            self.set_error_message(error_message)
        except ClientException, e3:
            print (e3)
            error_message = "No Mediagoblin instance found at this address"
            self.set_error_message(error_message)

    def set_error_message(self, error_message):
        self.error_message = ''
        self.error_message = error_message

    def check_token(self, verifier_token):
        self.verifier_token = verifier_token
        try:
            self.pump = verify_new_user(self.pump, self.verifier_token)
            self.pump.me.inbox[0]
            App.get_running_app().pump_service.pump = self.pump
            App.get_running_app().open_view('action', False)
            add_credential(USER_DIR, self.webfinger)
        except (PyPumpException, KeyError, IndexError, ReadTimeout), e:
            print (e)
            self.error_message = ''
            self.error_message = 'Verifier invalid, please try again'

    def update_pump(self):
        App.get_running_app().pump_service.pump = self.pump
        self.current_screen.welcome_text = 'Welcome, press enter to continue'
        print ('pump updated')


class LoginScreen(GoblinScreenWithManager):

    webfinger = StringProperty()
    verifier_token = StringProperty()
    verified = BooleanProperty(False)

    def __init__(self, **kwargs):
        super(LoginScreen, self).__init__(**kwargs)
        self.transition = SlideTransition(duration=.35)
        self.ids.sm.transition = self.transition
        self.ids.sm.open_screen(name='webfinger', class_name='webfinger')

    # after user is verified, allow user to enter app
    def enter_app(self):
        App.get_running_app().open_view('action', False)


class WebFinger(GoblinScreen):
    webfinger = StringProperty()
    error_message = StringProperty()

    def on_error_message(self, instance, value):
        print ('webfinger got error message: {0}'.format(value))


class Verify(GoblinScreen):
    verifier_token = StringProperty()
    error_message = ObjectProperty()
